﻿using System;
using System.Linq;
using System.Reflection;
using System.Web.Compilation;
using AspNetInfo.Core;
using System.Data;

namespace AspNetInfo.Detectors
{
    public class AssemblyDetector : IDetector
    {
        public string Name
        {
            get { return "Loaded Assemblies"; }
        }
        public string Description
        {
            get { return string.Empty; }
        }

        public string TabName
        {
            get { return Tabs.AspNet; }
        }

        public DataTable Detect(EnvironmentPermissions permissions)
        {
            var dt = DetectorHelper.MakeResultTable();

            var allAssemblies = BuildManager.GetReferencedAssemblies().OfType<Assembly>().Concat(AppDomain.CurrentDomain.GetAssemblies()).Distinct().OrderBy(o => o.FullName);
            foreach (var assembly in allAssemblies)
            {
                var key = assembly.FullName;
                var deployment = (assembly.GlobalAssemblyCache) ? "GAC" : "bin";
                var runtimeVersion = string.Empty;
                if (permissions.TrustLevel > System.Web.AspNetHostingPermissionLevel.Medium)
                {
                    runtimeVersion = assembly.ImageRuntimeVersion;
                }
                
                var codebase = "N/A";
                try
                {
                    codebase = assembly.CodeBase;
                }
                catch {}
                
                var value = String.Format("deployment: '{0}', codebase: '{1}', runtime: '{2}'", deployment, codebase, runtimeVersion);
                dt.Rows.Add(key, value);
            }
            
            return dt;
        }
    }
}